﻿using System.Text;
using UtilZ.Dotnet.Ex.Base;
using UtilZ.Dotnet.Ex.Communication.Net.Web;
using UtilZ.Dotnet.Ex.Log;

namespace UtilZFileServer
{
    internal class WebSiteIEResourceProvider : IWebSiteResourceProvider
    {
        private readonly Dictionary<string, string> _aliasPathDic = new Dictionary<string, string>();
        public WebSiteIEResourceProvider()
        {
            if (Config.Instance.ToolLocalPaths != null)
            {
                foreach (var item in Config.Instance.ToolLocalPaths)
                {
                    this._aliasPathDic.Add(item.Alias, item.Path);
                }
            }
        }


        /// <summary>
        /// 尝试获取站点资源，获取成功返回true[此时输出的资源文件路径和响应二选一，且响应优先级更高],获取失败返回false
        /// </summary>
        /// <param name="webSiteConfig">web站点配置</param>
        /// <param name="request">http请求</param>
        /// <param name="resourceFilePath">获取成功时的资源文件路径</param>
        /// <param name="response">获取成功时的响应,当响应不为null时直接使用此值响应输出</param>
        /// <returns>获取成功返回true,获取失败返回false</returns>
        public bool TryGetResource(WebSiteConfig webSiteConfig, HttpRequest request, out string resourceFilePath, out IHttpResponse response)
        {
            resourceFilePath = null;
            response = null;

            if (!IsIERequest(request))
            {
                //非IE请求直接返回                
                return false;
            }

            if (string.IsNullOrWhiteSpace(request.Url))
            {
                //url为空返回flase
                return false;
            }

            if (this._aliasPathDic != null && this._aliasPathDic.TryGetValue(Path.GetFileName(request.Url), out resourceFilePath))
            {
                //从别名中获取本地文件路径成功返回true
                return true;
            }

            //生成工具页面响应
            response = GenerateToolPageResponse(request);
            if (response != null)
            {
                return true;
            }

            //无工具页面则使用默认的IE自定义html页面
            if (request.Url.Length == 1 &&
                (request.Url.First() == Path.AltDirectorySeparatorChar || request.Url.First() == Path.DirectorySeparatorChar))
            {
                //请求地址为根目录,则使用默认页面
                string fileName = $"{Path.GetFileNameWithoutExtension(webSiteConfig.DefaultPageFilePath)}2{Path.GetExtension(webSiteConfig.DefaultPageFilePath)}";
                resourceFilePath = PathEx.Combine(PathType.Local, webSiteConfig.RootDir, fileName);
                return true;
            }

            resourceFilePath = null;
            return false;
        }

        private IHttpResponse GenerateToolPageResponse(HttpRequest request)
        {
            if (this._aliasPathDic == null || this._aliasPathDic.Count == 0)
            {
                return null;
            }

            StringBuilder sb = new StringBuilder();
            sb.AppendLine(@"<!DOCTYPE html>");
            sb.AppendLine(@"<html lang=""zh-cn"" xmlns=""http://www.w3.org/1999/xhtml"">");
            sb.AppendLine(@"<head>");
            sb.AppendLine(@"    <meta charset=""utf-8"" />");
            sb.AppendLine(@"    <title>文件管理器</title>");
            sb.AppendLine(@"</head>");
            sb.AppendLine(@"<body>");

            string localIPStr = NetHelper.GetIPPortString(request.Connection.LinkInfo.LocalEndPoint);
            if (Config.Instance.FtpCommandPort > 0)
            {
                sb.AppendLine($"<p><a href=\"ftp://{NetHelper.GetIPString(request.Connection.LinkInfo.LocalEndPoint)}:{Config.Instance.FtpCommandPort}\">FTP</a></p>");
            }

            foreach (var kv in this._aliasPathDic)
            {
                sb.AppendLine($"<p><a href=\"http://{localIPStr}/{kv.Key}\">{kv.Key}</a></p>");
            }

            sb.AppendLine(@"</body>");
            sb.AppendLine(@"</html>");

            //根据请求生成一个临时页面后返回true
            var httpResponse = new HttpResponse(request.Connection);
            httpResponse.SetBytes(HttpContentTypes.GetMimeMapping(".html"), request.GetClientTextEncoding(Encoding.UTF8).GetBytes(sb.ToString()));
            return httpResponse;
        }

        private static bool IsIERequest(HttpRequest request)
        {
            string userAgent;
            if (request.Headers.TryGetValue(HttpRequestHeaders.UserAgent, out userAgent))
            {
                /******************************************************************
                 * win10 IE11
                 * Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; rv
                 * 
                 * winxp IE6
                 * Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)
                 * 
                 * 
                 * win10 firefox
                 * Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv
                 * 
                 ******************************************************************/

                if (userAgent.Contains("MSIE", StringComparison.OrdinalIgnoreCase) ||
                    string.Equals(@"Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; rv", userAgent, StringComparison.OrdinalIgnoreCase))
                {
                    Loger.Info("客户端为IE浏览器");
                    return true;
                }
                else
                {
                    Loger.Info($"客户端为非IE浏览器\"{userAgent}\"");
                    return false;
                }
            }

            return false;
        }


    }
}
